import { ref } from 'vue'

// 创建loading状态
const loading = ref(false)

// 基础配置
const baseConfig = {
	// 121.40.132.119
    baseURL: 'http://121.40.132.119:8080',
    timeout: 40000,
    header: {
        'Content-Type': 'application/json'
    }
}

// 请求拦截器
const requestInterceptor = (config: any) => {
    // 获取token
    const token = uni.getStorageSync('token')

    if (token) {
        config.header = {
            ...config.header,
            'Authorization': `Bearer ${token.token}`
        }
    }


    return config
}

// 响应拦截器
const responseInterceptor = (response: any) => {

    // 处理响应
    if (response.statusCode === 200) {
        if (response.data.code === 200) {
            return response.data
        } else {
            // 处理业务错误
            uni.showToast({
                title: response.data.msg || '请求失败',
                icon: 'error',
                duration: 2000
            })
            return Promise.reject(response.data)
        }
    } else if (response.statusCode === 401) {
        // 未授权，清除token并跳转到登录页
        uni.removeStorageSync('token')
        uni.removeStorageSync('userInfo')
        uni.showToast({
            title: '登录已过期，请重新登录',
            icon: 'error',
            duration: 2000
        })
        setTimeout(() => {
            uni.navigateTo({
                url: '/pages/my/my'
            })
        }, 2000)
        return Promise.reject(response)
    } else {
        // 处理其他错误
        uni.showToast({
            title: '网络错误，请稍后重试',
            icon: 'error',
            duration: 2000
        })
        return Promise.reject(response)
    }
}

// 错误处理
const errorHandler = (error: any) => {

    uni.showToast({
        title: '网络错误，请稍后重试',
        icon: 'error',
        duration: 2000
    })

    return Promise.reject(error)
}

// 封装请求方法
const request = (options: any) => {
    const config = {
        ...baseConfig,
        ...options,
        url: baseConfig.baseURL + options.url
    }

    // 处理GET请求的参数
    if (config.method === 'GET' && config.params) {
        const queryString = Object.entries(config.params)
            .filter(([_, value]) => value !== undefined && value !== null)
            .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`)
            .join('&')

        if (queryString) {
            config.url += (config.url.includes('?') ? '&' : '?') + queryString
        }
        delete config.params
    }

    // 应用请求拦截器
    const interceptedConfig = requestInterceptor(config)

    return new Promise((resolve, reject) => {
        uni.request({
            ...interceptedConfig,
            success: (res: any) => {
                try {
                    const result = responseInterceptor(res)
                    resolve(result)
                } catch (error) {
                    reject(error)
                }
            },
            fail: (error: any) => {
                errorHandler(error)
                reject(error)
            }
        })
    })
}

// 封装常用请求方法
export const http = {
    get: (url: string, params?: any) => {
        return request({
            url,
            method: 'GET',
            params
        })
    },

    post: (url: string, data?: any, p0?: { timeout: number }) => {
        return request({
            url,
            method: 'POST',
            data
        })
    },

    put: (url: string, data?: any) => {
        return request({
            url,
            method: 'PUT',
            data
        })
    },

    delete: (url: string, data?: any) => {
        return request({
            url,
            method: 'DELETE',
            data
        })
    },

    // 头像上传
    upload: (url: string, filePath: string, name: string = 'file', formData?: any) => {
        const token = uni.getStorageSync('token')
        return new Promise((resolve, reject) => {
            uni.uploadFile({
                url: baseConfig.baseURL + url,
                filePath,
                name,
                formData,
                header: {
                    'Authorization': token ? `Bearer ${token}` : ''
                },
                success: (res) => {
                    try {
                        const result = JSON.parse(res.data)
                        if (result.code === 200) {
                            resolve(result)
                        } else {
                            uni.showToast({
                                title: result.msg || '上传失败',
                                icon: 'error',
                                duration: 2000
                            })
                            reject(result)
                        }
                    } catch (error) {
                        uni.showToast({
                            title: '上传失败',
                            icon: 'error',
                            duration: 2000
                        })
                        reject(error)
                    }
                },
                fail: (error) => {
                    uni.showToast({
                        title: '上传失败',
                        icon: 'error',
                        duration: 2000
                    })
                    reject(error)
                }
            })
        })
    }
}

export default http 